package com.yenlien.traceyun.business.service.rest.usercenter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.bean.RestURL;
import com.yenlien.traceyun.business.service.rest.RestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-07-21
 * @description:
 **/

@Service
public class FileRestService {

    @Autowired
    private RestService restService;

    /**
     * 上传
     *
     * @param files
     * @return
     */
    public String upload(List<MultipartFile> files) {
        return restService.postFile(RestURL.USERCENTER + "file/upload", files);
    }

    public String upload(MultipartFile file) {
        List<MultipartFile> files = new ArrayList<>();
        files.add(file);
        return restService.postFile(RestURL.USERCENTER + "file/upload", files);
    }

    public byte[] show(String fileName, String ys) {
        return restService.downFile(RestURL.USERCENTER + "file/show/" + fileName + "?ys=" + ys);
    }

    public JSONObject delete(String fileName) {
        return restService.getJson(RestURL.USERCENTER + "file/delete/" + fileName);
    }

    public String upload(List<MultipartFile> files, Object form) throws Exception {
        if (files == null || files.size() == 0) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        Field[] fields = form.getClass().getDeclaredFields();
        for (MultipartFile file : files) {
            for (Field field : fields) {
                String fileOrginalName = (file.getOriginalFilename());
                if (field.getName().toLowerCase().endsWith("img")) {
                    field.setAccessible(true);
                    Object fieldValue = field.get(form);
                    if (fieldValue != null) {
                        String oldValue = fieldValue.toString();
                        if (oldValue.contains(fileOrginalName)) {
                            String filename = upload(file).toString();
                            stringBuilder.append(";").append(filename);
                            field.set(form, oldValue.replace(fileOrginalName, filename));
                            break;
                        }
                    }
                }
            }
        }
        if (stringBuilder.length() <= 0) {
            return "";
        }
        return stringBuilder.substring(1);
    }

    private void replaceFileName(Object form, String originalFilename, String newName) throws IllegalAccessException {
        for (Field field : form.getClass().getDeclaredFields()) {
            if (field.getName().toLowerCase().endsWith("img")) {
                field.setAccessible(true);
                String oldValue = field.get(form).toString();
                if (oldValue != null && oldValue.contains(originalFilename)) {
                    field.set(form, oldValue.replace(originalFilename, newName));
                }
            }
        }
    }

    /**
     * @param persitent
     * @param form
     * @param files
     * @return
     */
    public String upload(Object persitent, Object form, List<MultipartFile> files) throws Exception {
        //添加
        if (persitent == null) {
            return upload(files, form);
        } else {//修改
            Field[] fields = form.getClass().getDeclaredFields();
            List<String> deles = new ArrayList<>();
            for (Field field : fields) {
                field.setAccessible(true);
                if (field.getName().toLowerCase().endsWith("img")) {
                    String newValue = field.get(form).toString();
                    Field oldField = persitent.getClass().getDeclaredField(field.getName());
                    oldField.setAccessible(true);
                    String oldValue = null;
                    Object oldObj = oldField.get(persitent);
                    if (oldObj != null) {
                        oldValue = oldObj.toString();
                    }
                    //如果新值为空则全部删除
                    if (StringUtils.isEmpty(newValue)) {
                        if (!StringUtils.isEmpty(oldValue)) {
                            deles.addAll(Arrays.asList(oldValue.split(";")));
                        }
                    } else {
                        if (!StringUtils.isEmpty(oldValue)) {
                            List<String> oldlist = new ArrayList(Arrays.asList(oldValue.split(";")));
                            List<String> newlist = new ArrayList(Arrays.asList(newValue.split(";")));
                            oldlist.removeAll(newlist);
                            if (oldlist.size() > 0) {
                                deles.addAll(oldlist);
                            }
                        }
                    }
                }
            }
            deleteFiles(deles);
            return upload(files, form);
        }
    }

    public void deleteFiles(List<String> files) throws IOException {
        if (files != null && files.size() > 0) {
            for (String filename : files) {
                delete(filename);
            }
        }
    }
}
